import axios from 'axios'
import extend from 'extend'
import hex_md5 from './../../../../tools/md5'
import * as config from './../define'
import iView from 'iview';
import {ZLST_WEB_LOCATION} from '@/api/service/config.js'

var CancelToken = axios.CancelToken;
var cancel;

var PROMISE_LIST = [];

// 添加请求拦截器
axios.interceptors.request.use(function (data) {
    // 在发送请求之前做些什么
    return data
}, function (error) {
    console.error(error);
    return ;
});

// http响应拦截器
axios.interceptors.response.use(data => {
    return  data;
}, error => {
    console.error(error)
    if(error != 'Cancel'){
        if (error.response && error.response.status == 401) { //登陆拦截
            iView.Message.warning('请登陆！');
            // window.location.href = ZLST_WEB_LOCATION.LOGIN_URL;
        }
        iView.Message.error('网络请求异常，请检查网络');
        error.status = error.response !=undefined ?error.response:'0';
        return error;
    } else {
        error.data = {code:1, errorMsg:'防重入。请求被拦截！'}
        return error;
    }

})

// 执行restful地址修改
String.prototype.restfulFormat = function (param) {
    let that = this;
    let keys = Object.keys(param);
    if (param === undefined || param === null || keys.length === 0) {
        return that;
    }
    for (let key of keys) {
        that = that.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
    }
    return that;
};

const commonMethods = {
    // 默认配置
    getDefaultConfig: function(){
        return {
            headers: {
                'Accept': 'application/json',
                // 'charset': 'UTF-8',
                // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8;',
                'token': window.localStorage.getItem('token')
            },
            cancelToken: new CancelToken(function executor(c) {
                // executor 函数接收一个 cancel 函数作为参数
                cancel = c;
            })
        };
    },
    // 将 JSON 格式转化为 formData
    toFormData: function(data) {
        var formData = new FormData();
        var fdKey = 0;
        //表单的值绑定formData
        for (var i in data) {
            if(i == 'append' || i == 'delete' || i== 'get'|| i== 'getAll' || i== 'has' || i== 'set' || i== 'keys' || i== 'values' || i== 'forEach' || i== 'entries'){
                fdKey ++
            }
            if (data[i] !== null || data[i] !== undefined || data[i] !== 'null' || data[i] !== 'undefined') {
                formData.append(i, data[i]);
            }
        }
        return fdKey<10? formData: data;
    },
    dodata: function(data) {
        var defaule ={};
        defaule.curTime = new Date().getTime();
        data = Object.assign({}, defaule, data);
        var strs = JSON.stringify(data);
        strs = strs.replace(/\"/g, "");
        strs = config.DEFAULTSIGNATUREPWD + strs;
        // console.log('加密字符串',strs)
        var sign = hex_md5(strs);
        data.tokenid =sign;
        return data;
    },
    formatUrl: function(Options, urlKey, args, cursor) {
        var result = '';
        var _cursor = cursor || 3;
        var restPath = args.slice(_cursor, args.length);
        if (restPath.length) {
            result = Options.baseUrl + Options.apiList[urlKey] + '/' + restPath.join('/');
        } else {
            result = Options.baseUrl + Options.apiList[urlKey];
        }
        return result;
    },
    // 验证params的组合配置项
    getConfig: function(config, Options){
        var _config = this.extendConfig(config, Options);
        if (_config.params) {
            _config = extend({}, _config, config);
        }
        else {
            _config.params = config || {};
        }
        return _config;
    },
    // 组合配置项
    extendConfig: function(config, Options){
        return extend({}, this.getDefaultConfig(), config || {}, { resetPathname: Options.resetPathname });
    },
    // 验证数据格式的config
    dataTypeConfig: function(config, data, Options){
        var dataType = config && config.dataType || '';
        var _data;
        var _config = this.extendConfig(config, Options);
        switch (dataType) {
            case 'formData':
                _data =this.toFormData(data);
            break;
            case 'json':
            default:
            _config.headers['Content-Type'] = 'application/json';
            _data = data;
            break;
        }
        return {"data":_data, "config": _config}
    }

}

export default commonMethods


